<template>
  <div>
    <!-- 图表 -->
    <div class="chart">
      <div class="chart-header task-flex task-ai">
        <div class="task-span1">
          <div class="chart-icon" :class="styles(chartType)"><i class="iconfont" :class="chartType"></i></div>
        </div>
        <div class="task-flex task-pointer">
          <div @click="exportBtn" class="task-export-text" v-show="type === $t('common.base.table2')">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.export') }}
          </div>
          <div @click="$emit('checkDate')" id="custom-report-data">
            <i class="iconfont icon-filter"></i>
            {{$t('report.customReportAggregate.title5')}}
            <i class="iconfont icon-triangle-down"></i>
          </div>
          <div class="task-ml12 task-pointer">
            <el-dropdown @command="handleClick">
              <div>
                <i class="iconfont icon-paixu1"></i>
                {{sort}}
                <i class="iconfont icon-triangle-down"></i>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="$t('report.productChart.defaultSort')">{{$t('report.productChart.defaultSort')}}</el-dropdown-item>
                <el-dropdown-item :command="$t('report.productChart.priceSort1')">{{$t('report.productChart.priceSort1')}}</el-dropdown-item>
                <el-dropdown-item :command="$t('report.productChart.priceSort1')">{{ $t('report.productChart.priceSort2') }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="task-ml12" @click="convertCanvasToImage" v-show="type !== $t('common.base.table2')">
            <i class="iconfont icon-cloud-download"></i>
            {{ $t('product.component.qrcodeDialog.btn2') }}
          </div>
        </div>
      </div>
      <no-data-view-new v-if="!chartList.length" :notice-msg="`${tableTitle && type ? $t('common.base.tip.noData') : $t('report.customReportAggregate.pla1')}`"></no-data-view-new>
      <!-- 图表 -->
      <div class="chart-content" id="custom-report-chart" v-if="type !== $t('common.base.table2') && chartList.length">
        <div id="chart"></div>
      </div>
      <!-- table -->
      <div :class="{'chart-table': chartList.length > 15}" v-if="type === $t('common.base.table2') && chartList.length">
        <el-table
          stripe
          border
          :data="chartList"
          ref="multipleTable"
          @row-click="tabletd"
          :row-class-name="rowClassName"
          header-row-class-name="common-list-table-header taks-list-table-header"
        >
          <el-table-column :label="tableTitle">
            <template slot-scope="scope">
              <div class="task-pointer">
                <template v-if="isOpenData && scope.row.staffId">
                  <open-data type='userName' :openid="scope.row.staffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row.name}}
                </template>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('report.customReportAggregate.total')">
            <template slot-scope="scope"><div class="task-pointer">{{scope.row.count}}</div></template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table task-mt12" v-show="tableNames.length">
      <div class="chart-header task-flex task-ai task-pointer">
        <div class="task-span1"></div>
        <div class="task-flex">
          <div @click="taskExport(false)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.export') }}
          </div>
          <div class="task-ml12" @click="taskExport(true)" v-if="isButtonDisplayed && exportAuth">
            <i class="iconfont icon-upload1"></i>
            {{ $t('common.base.exportAll') }}
          </div>
          <div class="task-ml12" @click="tableNames = []">
            {{ $t('common.base.collapse') }}
            <i class="iconfont icon-triangle-down"></i>
          </div>
        </div>
      </div> 

      <!-- S table -->
      <!-- 工单 -->
      <el-table
        v-if="reportType === 'task' || chartSatet === 1"
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in customizes"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            
            <template v-if="item.fieldName === 'taskNo'">
              <!-- 工单编号 -->
              <template>
                <a
                  href=""
                  class="view-detail-btn task-list-numbering"
                  @click.stop.prevent="openTaskTab(scope.row.id, scope.row[item.fieldName])"
                >
                  {{scope.row[item.fieldName]}}
                </a>
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'executorUserName'">
              <!-- 负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.executorUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.executorUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'createUserName'">
              <!-- 创建人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.createUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.createUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'horizontal'">
              <template v-if="isOpenData && scope.row.horizontalStaffId">
                <open-data type='userName' :openid="scope.row.horizontalStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.horizontal}}
              </template>
            </template>
            
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
            
          </template>
          
        </el-table-column>
      
      </el-table>
      <!-- 客户 -->
      <el-table
        v-else
        stripe
        border
        :data="tableNames"
        ref="multipleTable"
        header-row-class-name="common-list-table-header taks-list-table-header"
      >
        <el-table-column
          v-for="(item, index) in customercustomizes"
          :key="index"
          :label="item.displayName"
        >
          <template slot-scope="scope">
            
            <template v-if="item.fieldName === 'customerName'">
              <!-- 客户名称 -->
              <template>
                <a
                  href=""
                  class="view-detail-btn task-list-numbering"
                  @click.stop.prevent="openClientTab(scope.row)">
                  {{scope.row[item.fieldName]}}
                </a>
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'executorUserStaffId'">
              <!-- 负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.executorUserStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.executorUserName}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'horizontal'">
              <template v-if="isOpenData && scope.row.horizontalStaffId">
                <open-data type='userName' :openid="scope.row.horizontalStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.horizontal}}
              </template>
            </template>
            
            <template v-else-if="item.fieldName === 'customerManagerName'">
              <!-- 客户负责人 -->
              <template v-if="isOpenData">
                <open-data type='userName' :openid="scope.row.customerManagerStaffId"></open-data>
              </template>
              <template v-else>
                {{scope.row.customerManagerName}}
              </template>
            </template>
            
            <template v-else>
              {{scope.row[item.fieldName]}}
            </template>
            
          </template>
          
        </el-table-column>
      </el-table>
      <!-- E table -->
      <!-- 分页 -->
      <div class="spare-parts-foot task-flex task-ai report-spare-parts-foot">
        <span class="task-c90">{{$t('report.system.total',{num:pagination.total})}}</span>
        <el-pagination
          class="comment-list-table-footer-pagination task-span1"
          background
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="pageSize"
          :total="pagination.total"
          :current-page="pageNum"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          layout="prev, pager, next, sizes, jumper"
        >
        </el-pagination>
      </div>  
    </div>
  </div>
</template>
<script>
import { t } from '@src/locales';
import { isOpenData, openAccurateTab } from '@src/util/platform';
import echarts from 'packages/Echarts';
import NoDataViewNew from '@src/component/common/NoDataViewNew';

import {CUSTOMIZE, CUSTOMERCUSTOMIZE} from '../../common/tableModel'
import {COLORS} from '../../common/colorLModel'

import { formatDate } from 'pub-bbx-utils';

import * as ReportApi from '@src/api/ReportApi.ts';

import { isEmpty } from '@src/util/type'

import { checkButtonDisplayed } from '@src/util/dom';
import { safeNewDate } from '@src/util/time';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'
export default {
  name: 'chart',
  props: {
    type: {
      type: String // 图表类型
    },
    chartList: {
      type: Array
    }, // 数据
    parasm: {
      type: Object
    }, // 参数
    chartSatet:{
      type: Number | String
    }, // 生成的报表判断
    sorts: {
      type: Array | String
    }, // 默认排序
  },
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      chartType: '', // 图表icon
      reportType: '', // 报表类型
      sort: t('report.productChart.defaultSort'),
      pageSize: 10,
      pageNum: 1,
      tableNames: [],
      pagination: {},
      productType: '',
      exportPage: 0,
      dataIndex: 0,
      exportParams: {},
      tableTitle: '',
      customizes:CUSTOMIZE,
      customercustomizes: CUSTOMERCUSTOMIZE
    }
  },
  computed: {
    exportAuth() {
      let initData = JSON.parse(sessionStorage.getItem('_init_data'))
      return initData.auths?.REPORT_EXPORT || 0
    },
    // 是否是工单自定义报表
    isTaskReport(){
      return this.reportType === 'task' || this.chartSatet === 1;
    },
  },
  watch: {
    type(v) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      if (v === t('common.base.histogram')) {
        this.chartType = 'icon-signal-fill'
        if (this.chartList.length) this.histogram(this.chartList)
      } else if (v === t('common.base.pieChart')) {
        this.chartType = 'icon-piechart-circle-fil'
        if (this.chartList.length) this.pieChart(this.chartList)
      } else if (v == t('common.base.lineChart')) {
        this.chartType = 'icon-fund-fill'
        if (this.chartList.length) this.lineChart(this.chartList)  
      } else {
        this.chartType = 'icon-detail-fill'
        if (this.chartList.length) {
          const myChart = echarts.init(document.getElementById('chart'))
          myChart.clear()
        }
      }
    },
    chartList(v) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      this.initialization()
    }
  },
  mounted() {
    let urlParams = {}
    window.location.href.split('?')[1].split('&').forEach(item => {
      urlParams[item.split('=')[0]] = item.split('=')[1]
    })

    this.reportType = urlParams.type
    this.initialization()

    if (this.type === t('common.base.histogram')) {
      this.chartType = 'icon-signal-fill'
    } else if (this.type === t('common.base.pieChart')) {
      this.chartType = 'icon-piechart-circle-fil'
    } else if (this.type == t('common.base.lineChart')) {
      this.chartType = 'icon-fund-fill'
    } else {
      this.chartType = 'icon-detail-fill'
    }

    if (this.sorts) {
      if (this.sorts.direction) {
        this.sort = t('report.productChart.priceSort2')
      } else {
        this.sort = t('report.productChart.priceSort1')
      }
    }
  },
  methods: {
    stateText(item) {
      if (isEmpty(item)) return
      
      this.tableTitle = item[0].value
      this.customercustomizes = CUSTOMERCUSTOMIZE.map((v, index) => {
        if(!index) v.displayName = item[0].value 
        return v
      })
      this.customizes = CUSTOMIZE.map((v, index) => {
        if(!index) v.displayName = item[0].value 
        return v
      })
    },
    // 初始化
    initialization() {
      if (!this.chartList.length) return
      if (this.type === t('common.base.histogram')) {
        this.histogram(this.chartList)
      } else if (this.type === t('common.base.pieChart')) {
        this.pieChart(this.chartList)
      } else if (this.type == t('common.base.lineChart')) {
        this.lineChart(this.chartList)
      }
    },
    // 排序
    handleClick(v) {
      this.sort = v
      let sorts
      switch (v) {
      case t('report.productChart.priceSort1'):
        sorts = [{'property':'total', 'direction':'DESC'}]
        break;
      case t('report.productChart.priceSort2'):
        sorts = [{'property':'total', 'direction':'ASC'}]
        break;      
      default:
        sorts = ''
        break;
      }
      this.tableNames = []
      this.$emit('taskTable', {
        sorts,
      })
    },
    // 转成图片并下载
    convertCanvasToImage() {
      const canvas = document.querySelector('#chart div canvas')
      const img = canvas.toDataURL('image/png');
      const oA = document.createElement('a');
      // TODO国际化翻译拼接待办
      oA.download = `${this.type}统计图表`;// 设置下载的文件名，默认是'下载'
      oA.href = img;
      document.body.appendChild(oA);
      oA.click();
      oA.remove();
    },
    rowClassName({row, rowIndex}) {
      this.$set(row, 'dataIndex', rowIndex)
    },
    // 表格
    tabletd(e) {
      this.tableNames = []
      this.pageSize = 10
      this.pageNum = 1
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage(e)
      } else if (this.reportType === 'product') {} 
      else {
        this.aggregationData(e)
      }    
    },
    // 柱状图
    histogram(data) {
      this.$nextTick(() => {
        const myChart = echarts.init(document.getElementById('chart'))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            data: data.map(item => {return item.name}),
          },
          yAxis: {
            type: 'value',
          },
          dataZoom: [
            {
              show: true,
              start: 0,
              end: data.length < 10 ? 100 : 3
            }
          ],
          series: [{
            data: data.map(item => {return item.count}),
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            },
            barCateGoryGap:20,
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd(e)
        })
      })
    },
    // 饼图
    pieChart(data) {
      this.$nextTick(() => {
        const myChart = echarts.init(document.getElementById('chart'))
        const option = {
          color: COLORS,
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            data: data.map(item => {return item.name})
          },
          series: [
            {
              name: t('report.customReportAggregate.resource'),
              type: 'pie',
              radius: '55%',
              center: ['50%', '60%'],
              data: data.map(item => {item.value = item.count; return item}),
              label: {
                normal: {
                  show: true,
                  formatter: '{b} : {c} ({d}%)'
                }
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd({name: e.name, data: e.data.value, dataIndex: e.dataIndex})
        })
      })
    },
    // 折线图
    lineChart(data) {
      this.$nextTick(() => {
        const myChart = echarts.init(document.getElementById('chart'))
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{b} : {c} '
          },
          xAxis: {
            type: 'category',
            data: data.map(item => {return item.name}),
          },
          yAxis: {
            type: 'value',
          },
          dataZoom: [
            {
              show: true,
              start: 0,
              end: data.length < 10 ? 100 : 3
            }
          ],
          series: [{
            data: data.map(item => {return item.count}),
            type: 'line',
            barWidth : 30,
            itemStyle: {
              normal: {
                color: '#55b7b4'
              }
            },
            label: {
              show: true,
              position: 'top',
            }
          }],
          backgroundColor: '#fff'
        };
        myChart.setOption(option, true);
        myChart.off('click')
        myChart.on('click', e => {
          this.tabletd(e)
        })
      })
    },
    // 工单：根据关键字查询工单信息-分页
    async aggregationPage(e) {
      this.$loading.service()
      let item = this.chartList.filter((item, index) => {
        // 单纯按名称来筛选会筛选出错误的数据，所以额外加了按index条件
        return e.name === item.name && e.dataIndex === index
      })[0]
      const {pageSize, pageNum} = this
      this.productType = item.name
      this.exportPage = e.data || e.count
      this.dataIndex = e.dataIndex

      const params = {...this.parasm, aggregationValue: item.id, pageSize, page: pageNum}
      this.exportParams = params
      const {result, success} = await ReportApi.aggregationPage(params)

      this.$loading.service().close()
      if (!success) return
      const {list, total} = result
      this.tableNames = list.map(v => {
        v.horizontal = item.name
        v.horizontalStaffId = item.staffId
        v.createDateTime = formatDate(safeNewDate(v.createDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss')
        return v
      })
      this.pagination = {
        total,
      };
    },
    // 客户：根据关键字查询工单信息-分页
    async aggregationData(e) {
      let item = this.chartList.filter(item => {return e.name === item.name})[0]
      const {pageSize, pageNum} = this
      this.productType = item.name
      this.exportPage = e.data || e.count

      this.$loading.service()

      const params = {...this.parasm, aggregationValue: item.id, pageSize, page: pageNum}
      this.exportParams = params
      const {result, success} = await ReportApi.aggregationData(params)

      this.$loading.service().close()
      if (!success) return
      const {list, total} = result
      this.tableNames = list.map(v => {
        v.horizontal = item.name
        v.horizontalStaffId = item.staffId
        v.createDateTime = formatDate(safeNewDate(v.createDateTime).getTime(), 'YYYY-MM-DD HH:mm:ss')
        return v
      })
      this.pagination = {
        total,
      };   
    },
    clons() {
      this.tableNames = []
    },
    /**
     * @description 打开工单详情tab
     * @param {String} taskId 工单id
     */
    openTaskTab(taskId, taskNo) {
      if (!taskId) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   url: `/task/view/${taskId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        params: 'noHistory=1',
        fromId
      })
    },
    /**
     *
     * @description 打开客户详情
     * @param {object} clientInfo 客户详情
     */
    openClientTab({id}) {
  
      if (!id) return;

      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `customer_view_${id}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${id}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: id,
        params: 'noHistory=1',
        fromId
      })
    },
    // 导出
    async taskExport(type) {
      this.$loading.service()

      delete this.exportParams.page

      let pageSize
      if (type) {
        pageSize = this.chartList.reduce((c, s) => {return c += s.count}, 0)
      } else {
        pageSize = this.exportPage
      }

      let params = {...this.exportParams, ...{pageNum: 1, pageSize, aggregationFieldName: this.tableNames.map(item => {return item.horizontal})[0]}}
      if (type) delete params.aggregationValue
        
      if (this.reportType === 'task' || this.chartSatet === 1) {
        await this.$http.post('/excels/custom/taskExport', params)
      } else if (this.reportType === 'product') {} 
      else {
        await this.$http.post('/excels/custom/customerExport', params)
      }
      window.parent.showExportList();
      window.parent.exportPopoverToggle(true);

      this.$loading.service().close()
    },
    /* 分页条数切换 */
    handleSizeChange(value) {
      this.pageNum = 1
      this.pageSize = value;
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage({name: this.productType, data: this.exportPage, dataIndex: this.dataIndex})
      } else if (this.reportType === 'product') {} 
      else {
        this.aggregationData({name: this.productType, data: this.exportPage})
      }
    },
    /* 分页页数切换 */
    handlePageChange(value) {
      this.pageNum = value;
      if (this.reportType === 'task' || this.chartSatet === 1) {
        this.aggregationPage({name: this.productType, data: this.exportPage, dataIndex: this.dataIndex})
      } else if (this.reportType === 'product') {} 
      else {
        this.aggregationData({name: this.productType, data: this.exportPage})
      }
    },
    // 样式
    styles(icon) {
      let sty;
      if (icon === 'icon-ditu2') {
        sty = 'task-bj9f'
      } else if (icon === 'icon-piechart-circle-fil') {
        sty = 'task-bjf7'
      } else if (icon === 'icon-fund-fill') {
        sty = 'task-bjd1'
      } else if (icon === 'icon-detail-fill' || icon === 'icon-calendar-fill') {
        sty = 'task-bjc4'
      } else {
        sty = 'task-bjc2'
      }
      return sty
    },
    // 导出
    async exportBtn(){
      try{
        if(this.chartList.length > 10000) return this.$platform.alert(t('product.qrcode.tips.tip12',{count:10000}));
        this.$loading.service();

        // 工单和客户使用不同接口导出
        const api = this.isTaskReport ? 'taskReportExport' : 'customReportExport';
        const { code, result: message } = await ReportApi[api](this.parasm);

        if(code === 0){
          this.$message.success(message);
          window.parent.showExportList()
          window.parent.exportPopoverToggle(true)
        }else {
          this.$platform.alert(message);
        }
        this.$loading.service().close();
      }catch(e){
        console.log('exportBtn', e);
        this.$loading.service().close();
      }
    },
  },
  components: {
    [NoDataViewNew.name]: NoDataViewNew
  }
}
</script>
<style lang="scss" scoped>

.chart-header {
    color: rgba(0, 0, 0, 0.65);
    height: 56px;
    background-color:#FAFAFA;
    padding: 0 12px;
    font-size: 14px;
    border-radius: 4px 4px 0 0;
    border-right: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    .iconfont {
        font-size: 14px;
    }
    .chart-icon {
      width: 32px;
      height: 32px;
      border-radius: 4px;
      text-align: center;
      line-height: 32px;
      color: #fff;
    }
}
.chart-content {
    background-color: #fff;
    width: 100%;
    height: 400px;
    padding: 12px;
    border-right: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
    #chart {
        width: 100%;
        height: 100%;
    }
}
.guide-point{
  background-color: white
}
.chart > .guide-point {
  margin-top: 30px;
}
.chart-table {
  max-height: 500px;
  overflow: hidden;
  overflow-y: scroll;
}
.spare-parts-foot {
    margin: 12px 0 12px 0;
}
.task-export-text {
  margin-right: 20px;
}
</style>